package org.jflame.commons.convert;

import org.jflame.commons.util.CollectionHelper;
import org.jflame.commons.util.DateHelper;
import org.jflame.commons.util.StringHelper;

import java.util.Date;
import java.util.Set;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;

/**
 * 时间格式化
 * 
 * @author charles.zhang
 */
public class DateToStringConverter implements Converter<Date,String>, ConvertibleType {

    private String datePattern = null;

    public DateToStringConverter() {
    }

    public DateToStringConverter(String datePattern) {
        StringHelper.requireNonEmpty(datePattern, "'datePattern' must not be empty");
        this.datePattern = datePattern;
    }

    @Override
    public String convert(Date source) {
        if (source instanceof java.sql.Date) {
            return DateFormatUtils.format(source, datePattern != null ? datePattern : DateHelper.YYYY_MM_DD);
        } else if (source instanceof java.sql.Time) {
            return DateFormatUtils.format(source, datePattern != null ? datePattern : DateHelper.HH_mm_ss);
        } else {
            return DateFormatUtils.format(source, datePattern != null ? datePattern : DateHelper.YYYY_MM_DD_HH_mm_ss);
        }
    }

    @Override
    public Set<ImmutablePair<Class<?>,Class<?>>> getConvertibleTypes() {
        return CollectionHelper.newLinkedHashSet(ImmutablePair.of(Date.class, String.class),
                ImmutablePair.of(java.sql.Date.class, String.class),
                ImmutablePair.of(java.sql.Time.class, String.class),
                ImmutablePair.of(java.sql.Timestamp.class, String.class));
    }

}
